//
//  SettingsViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import UIKit

class SettingsViewController: UIViewController {
    
    // MARK: - UI Components
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    
    private let proBannerView = UIView()
    private let proBannerLabel = UILabel()
    private let proBannerSubLabel = UILabel()
    private let learnMoreButton = UIButton(type: .system)
    
    private let basicSettingsView = UIView()
    private let basicSettingsLabel = UILabel()
    private let basicSettingsStackView = UIStackView()
    
    private let aboutView = UIView()
    private let aboutLabel = UILabel()
    private let aboutStackView = UIStackView()
    
    // MARK: - Data Models
    private struct SettingItem {
        let icon: String
        let title: String
        let isPro: Bool
        let controlType: ControlType
        let hasInfo: Bool
        
        enum ControlType {
            case toggle(Bool)
            case text(String)
            case button(String, String?) // text, proTag
        }
    }
    
    private func getBasicSettings() -> [SettingItem] {
        return [
            SettingItem(icon: "📋", title: "历史记录", isPro: false, controlType: .text(""), hasInfo: false),
            SettingItem(icon: "🌙", title: "暗黑模式", isPro: false, controlType: .toggle(ThemeManager.shared.isDarkMode), hasInfo: false),
            SettingItem(icon: "📄", title: "用户协议", isPro: false, controlType: .text(""), hasInfo: false),
            SettingItem(icon: "🔒", title: "隐私协议", isPro: false, controlType: .text(""), hasInfo: false),
//            SettingItem(icon: "🗑️", title: "历史记录保留", isPro: false, controlType: .button("近50条", nil), hasInfo: false),
            SettingItem(icon: "🔧", title: "技术支持", isPro: false, controlType: .text(""), hasInfo: false)
        ]
    }
    
    private let aboutSettings: [SettingItem] = [
//        SettingItem(icon: "⭐", title: "五星好评", isPro: false, controlType: .text(""), hasInfo: false),
        SettingItem(icon: "ℹ️", title: "关于我们", isPro: false, controlType: .text(""), hasInfo: false),
        SettingItem(icon: "📤", title: "分享给朋友", isPro: false, controlType: .text(""), hasInfo: false),
        
    ]
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 隐藏导航栏
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 显示导航栏（当离开页面时）
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return ThemeManager.shared.isDarkMode ? .lightContent : .darkContent
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        // 设置页面背景色 - 浅色模式透明，暗黑模式深色
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : kAppColor
        
        setupProBanner()
        setupBasicSettings()
        setupAboutSection()
        setupScrollView()
        
        // 监听主题变化
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    

    
    private func setupProBanner() {
        let isDark = ThemeManager.shared.isDarkMode
        proBannerView.backgroundColor = ThemeManager.Colors.proBannerBackground(for: isDark)
        proBannerView.layer.cornerRadius = 12
        proBannerView.layer.borderWidth = 1
        proBannerView.layer.borderColor = UIColor.systemGreen.cgColor
        
        proBannerLabel.text = "智能扫描仪"
        proBannerLabel.font = UIFont.boldSystemFont(ofSize: 16)
        proBannerLabel.textColor = .systemGreen
        
        proBannerSubLabel.text = "让文档处理更简单高效"
        proBannerSubLabel.font = UIFont.systemFont(ofSize: 14)
        proBannerSubLabel.textColor = .white
        
        learnMoreButton.setTitle("使用指南", for: .normal)
        learnMoreButton.setTitleColor(.white, for: .normal)
        learnMoreButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        learnMoreButton.addTarget(self, action: #selector(learnMoreTapped), for: .touchUpInside)
        
        proBannerView.addSubview(proBannerLabel)
        proBannerView.addSubview(proBannerSubLabel)
        proBannerView.addSubview(learnMoreButton)
    }
    
    private func setupBasicSettings() {
        let isDark = ThemeManager.shared.isDarkMode
        basicSettingsView.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        basicSettingsView.layer.cornerRadius = 12
        
        basicSettingsLabel.text = "基本设置"
        basicSettingsLabel.font = UIFont.boldSystemFont(ofSize: 18)
        basicSettingsLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        basicSettingsStackView.axis = .vertical
        basicSettingsStackView.spacing = 0
        
        for item in getBasicSettings() {
            let itemView = createSettingItemView(item: item)
            basicSettingsStackView.addArrangedSubview(itemView)
        }
        
        basicSettingsView.addSubview(basicSettingsLabel)
        basicSettingsView.addSubview(basicSettingsStackView)
    }
    
    private func setupAboutSection() {
        let isDark = ThemeManager.shared.isDarkMode
        aboutView.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        aboutView.layer.cornerRadius = 12
        
        aboutLabel.text = "关于"
        aboutLabel.font = UIFont.boldSystemFont(ofSize: 18)
        aboutLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        aboutStackView.axis = .vertical
        aboutStackView.spacing = 0
        
        for item in aboutSettings {
            let itemView = createSettingItemView(item: item)
            aboutStackView.addArrangedSubview(itemView)
        }
        
        aboutView.addSubview(aboutLabel)
        aboutView.addSubview(aboutStackView)
    }
    
    private func setupScrollView() {
        scrollView.showsVerticalScrollIndicator = false
        let isDark = ThemeManager.shared.isDarkMode
//        scrollView.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : .clear
        contentView.backgroundColor = .clear
        
        contentView.addSubview(proBannerView)
        contentView.addSubview(basicSettingsView)
        contentView.addSubview(aboutView)
        
        scrollView.addSubview(contentView)
        view.addSubview(scrollView)
    }
    
    private func createSettingItemView(item: SettingItem) -> UIView {
        let containerView = UIView()
        containerView.backgroundColor = .clear
        containerView.isUserInteractionEnabled = true
        
        let iconLabel = UILabel()
        iconLabel.text = item.icon
        iconLabel.font = UIFont.systemFont(ofSize: 20)
        
        let titleLabel = UILabel()
        titleLabel.text = item.title
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        let isDark = ThemeManager.shared.isDarkMode
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        let proTag = createProTag()
        proTag.isHidden = !item.isPro
        
        let infoButton = UIButton(type: .system)
        infoButton.setImage(UIImage(systemName: "info.circle.fill"), for: .normal)
        infoButton.tintColor = .systemBlue
        infoButton.isHidden = !item.hasInfo
        infoButton.addTarget(self, action: #selector(infoButtonTapped), for: .touchUpInside)
        
        containerView.addSubview(iconLabel)
        containerView.addSubview(titleLabel)
        containerView.addSubview(proTag)
        containerView.addSubview(infoButton)
        
        // 根据控制类型添加不同的控件
        switch item.controlType {
        case .toggle(let isOn):
            let toggle = UISwitch()
            toggle.isOn = isOn
            toggle.onTintColor = .systemGreen
            toggle.addTarget(self, action: #selector(toggleChanged(_:)), for: .valueChanged)
            toggle.addTarget(self, action: #selector(toggleTouchDown(_:)), for: .touchDown)
            print("Created toggle with isOn: \(isOn)")
            
            toggle.isUserInteractionEnabled = true
            containerView.addSubview(toggle)
            toggle.translatesAutoresizingMaskIntoConstraints = false
            
            NSLayoutConstraint.activate([
                toggle.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
                toggle.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
            ])
            
            // 添加约束后的调试信息
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                print("Toggle final frame: \(toggle.frame)")
                print("Toggle is user interaction enabled: \(toggle.isUserInteractionEnabled)")
                print("Toggle alpha: \(toggle.alpha)")
                print("Toggle is hidden: \(toggle.isHidden)")
            }
            
        case .text(let text):
            let label = UILabel()
            label.text = text
            label.font = UIFont.systemFont(ofSize: 14)
            label.textColor = .gray
            
            let chevron = UIImageView(image: UIImage(systemName: "chevron.right"))
            chevron.tintColor = .gray
            chevron.contentMode = .scaleAspectFit
            
            // 为整个容器添加点击手势
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(settingItemTapped(_:)))
            containerView.addGestureRecognizer(tapGesture)
            containerView.isUserInteractionEnabled = true
            
            // 存储标题信息用于识别点击的项目
            containerView.tag = item.title.hashValue
            
            containerView.addSubview(label)
            containerView.addSubview(chevron)
            
            label.translatesAutoresizingMaskIntoConstraints = false
            chevron.translatesAutoresizingMaskIntoConstraints = false
            
            NSLayoutConstraint.activate([
                label.trailingAnchor.constraint(equalTo: chevron.leadingAnchor, constant: -4),
                label.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                
                chevron.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
                chevron.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                chevron.widthAnchor.constraint(equalToConstant: 12),
                chevron.heightAnchor.constraint(equalToConstant: 12)
            ])
            
        case .button(let text, let proTag):
            let button = UIButton(type: .system)
            button.setTitle(text, for: .normal)
            button.setTitleColor(.systemGreen, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.backgroundColor = UIColor.systemGreen.withAlphaComponent(0.1)
            button.layer.cornerRadius = 12
            button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12)
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            
            containerView.addSubview(button)
            button.translatesAutoresizingMaskIntoConstraints = false
            
            if let proTag = proTag {
                let proLabel = UILabel()
                proLabel.text = proTag
                proLabel.font = UIFont.boldSystemFont(ofSize: 10)
                proLabel.textColor = .systemGreen
                proLabel.textAlignment = .center
                proLabel.backgroundColor = UIColor.systemGreen.withAlphaComponent(0.1)
                proLabel.layer.cornerRadius = 8
                proLabel.layer.masksToBounds = true
                
                containerView.addSubview(proLabel)
                proLabel.translatesAutoresizingMaskIntoConstraints = false
                
                NSLayoutConstraint.activate([
                    button.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
                    button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    
                    proLabel.leadingAnchor.constraint(equalTo: button.trailingAnchor, constant: 8),
                    proLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    proLabel.widthAnchor.constraint(equalToConstant: 30),
                    proLabel.heightAnchor.constraint(equalToConstant: 18),
                    
                    containerView.trailingAnchor.constraint(equalTo: proLabel.trailingAnchor)
                ])
            } else {
                NSLayoutConstraint.activate([
                    button.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
                    button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    containerView.trailingAnchor.constraint(equalTo: button.trailingAnchor)
                ])
            }
        }
        
        // Layout constraints
        iconLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        proTag.translatesAutoresizingMaskIntoConstraints = false
        infoButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            iconLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            iconLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            iconLabel.widthAnchor.constraint(equalToConstant: 24),
            iconLabel.heightAnchor.constraint(equalToConstant: 24),
            
            titleLabel.leadingAnchor.constraint(equalTo: iconLabel.trailingAnchor, constant: 12),
            titleLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            
            proTag.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 8),
            proTag.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            
            infoButton.leadingAnchor.constraint(equalTo: proTag.trailingAnchor, constant: 8),
            infoButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            infoButton.widthAnchor.constraint(equalToConstant: 20),
            infoButton.heightAnchor.constraint(equalToConstant: 20),
            
            containerView.heightAnchor.constraint(equalToConstant: 56)
        ])
        
        return containerView
    }
    
    private func createProTag() -> UIView {
        let tagView = UIView()
        tagView.backgroundColor = .systemGreen
        tagView.layer.cornerRadius = 8
        
        let label = UILabel()
        label.text = "Pro"
        label.font = UIFont.boldSystemFont(ofSize: 10)
        label.textColor = .white
        label.textAlignment = .center
        
        tagView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: tagView.leadingAnchor, constant: 6),
            label.trailingAnchor.constraint(equalTo: tagView.trailingAnchor, constant: -6),
            label.topAnchor.constraint(equalTo: tagView.topAnchor, constant: 2),
            label.bottomAnchor.constraint(equalTo: tagView.bottomAnchor, constant: -2),
            
            tagView.widthAnchor.constraint(greaterThanOrEqualToConstant: 30),
            tagView.heightAnchor.constraint(equalToConstant: 18)
        ])
        
        return tagView
    }
    
    private func createControlView(for controlType: SettingItem.ControlType) -> UIView {
        let containerView = UIView()
        containerView.isUserInteractionEnabled = true
        
        switch controlType {
        case .toggle(let isOn):
            let toggle = UISwitch()
            toggle.isOn = isOn
            toggle.onTintColor = .systemGreen
            toggle.addTarget(self, action: #selector(toggleChanged(_:)), for: .valueChanged)
            toggle.addTarget(self, action: #selector(toggleTouchDown(_:)), for: .touchDown)
            print("Created toggle with isOn: \(isOn)")
            
            // 添加更多调试信息
            toggle.isUserInteractionEnabled = true
            print("Toggle user interaction enabled: \(toggle.isUserInteractionEnabled)")
            
            containerView.addSubview(toggle)
            
            // 在添加到父视图后打印信息
            print("Toggle frame after adding: \(toggle.frame)")
            print("Toggle superview after adding: \(toggle.superview?.description ?? "nil")")
            toggle.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                toggle.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
                toggle.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                toggle.widthAnchor.constraint(equalToConstant: 51),
                toggle.heightAnchor.constraint(equalToConstant: 31),
                
                // 给 controlView 添加明确的宽度约束
                containerView.widthAnchor.constraint(equalToConstant: 67), // 51 + 16 边距
                containerView.heightAnchor.constraint(equalToConstant: 31)
            ])
            
            // 添加约束后的调试信息
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                print("Toggle final frame: \(toggle.frame)")
                print("Toggle is user interaction enabled: \(toggle.isUserInteractionEnabled)")
                print("Toggle alpha: \(toggle.alpha)")
                print("Toggle is hidden: \(toggle.isHidden)")
            }
            
        case .text(let text):
            let label = UILabel()
            label.text = text
            label.font = UIFont.systemFont(ofSize: 14)
            label.textColor = .gray
            
            let chevron = UIImageView(image: UIImage(systemName: "chevron.right"))
            chevron.tintColor = .gray
            chevron.contentMode = .scaleAspectFit
            
            containerView.addSubview(label)
            containerView.addSubview(chevron)
            
            label.translatesAutoresizingMaskIntoConstraints = false
            chevron.translatesAutoresizingMaskIntoConstraints = false
            
            NSLayoutConstraint.activate([
                label.trailingAnchor.constraint(equalTo: chevron.leadingAnchor, constant: -4),
                label.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                
                chevron.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
                chevron.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                chevron.widthAnchor.constraint(equalToConstant: 12),
                chevron.heightAnchor.constraint(equalToConstant: 12)
            ])
            
        case .button(let text, let proTag):
            let button = UIButton(type: .system)
            button.setTitle(text, for: .normal)
            button.setTitleColor(.systemGreen, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.backgroundColor = UIColor.systemGreen.withAlphaComponent(0.1)
            button.layer.cornerRadius = 12
            button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12)
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            
            containerView.addSubview(button)
            button.translatesAutoresizingMaskIntoConstraints = false
            
            if let proTag = proTag {
                let proLabel = UILabel()
                proLabel.text = proTag
                proLabel.font = UIFont.boldSystemFont(ofSize: 10)
                proLabel.textColor = .systemGreen
                proLabel.textAlignment = .center
                proLabel.backgroundColor = UIColor.systemGreen.withAlphaComponent(0.1)
                proLabel.layer.cornerRadius = 8
                proLabel.layer.masksToBounds = true
                
                containerView.addSubview(proLabel)
                proLabel.translatesAutoresizingMaskIntoConstraints = false
                
                NSLayoutConstraint.activate([
                    button.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
                    button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    
                    proLabel.leadingAnchor.constraint(equalTo: button.trailingAnchor, constant: 8),
                    proLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    proLabel.widthAnchor.constraint(equalToConstant: 30),
                    proLabel.heightAnchor.constraint(equalToConstant: 18),
                    
                    containerView.trailingAnchor.constraint(equalTo: proLabel.trailingAnchor)
                ])
            } else {
                NSLayoutConstraint.activate([
                    button.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
                    button.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
                    containerView.trailingAnchor.constraint(equalTo: button.trailingAnchor)
                ])
            }
        }
        
        return containerView
    }
    
    // MARK: - Constraints
    private func setupConstraints() {
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.translatesAutoresizingMaskIntoConstraints = false
        proBannerView.translatesAutoresizingMaskIntoConstraints = false
        basicSettingsView.translatesAutoresizingMaskIntoConstraints = false
        aboutView.translatesAutoresizingMaskIntoConstraints = false
        proBannerLabel.translatesAutoresizingMaskIntoConstraints = false
        proBannerSubLabel.translatesAutoresizingMaskIntoConstraints = false
        learnMoreButton.translatesAutoresizingMaskIntoConstraints = false
        basicSettingsLabel.translatesAutoresizingMaskIntoConstraints = false
        basicSettingsStackView.translatesAutoresizingMaskIntoConstraints = false
        aboutLabel.translatesAutoresizingMaskIntoConstraints = false
        aboutStackView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // ScrollView
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            
            // ContentView
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
            
            // ProBanner
            proBannerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16),
            proBannerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            proBannerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            proBannerView.heightAnchor.constraint(equalToConstant: 80),
            
            proBannerLabel.leadingAnchor.constraint(equalTo: proBannerView.leadingAnchor, constant: 16),
            proBannerLabel.topAnchor.constraint(equalTo: proBannerView.topAnchor, constant: 16),
            
            proBannerSubLabel.leadingAnchor.constraint(equalTo: proBannerView.leadingAnchor, constant: 16),
            proBannerSubLabel.topAnchor.constraint(equalTo: proBannerLabel.bottomAnchor, constant: 8),
            
            learnMoreButton.trailingAnchor.constraint(equalTo: proBannerView.trailingAnchor, constant: -16),
            learnMoreButton.centerYAnchor.constraint(equalTo: proBannerView.centerYAnchor),
            
            // BasicSettings
            basicSettingsView.topAnchor.constraint(equalTo: proBannerView.bottomAnchor, constant: 16),
            basicSettingsView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            basicSettingsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            
            basicSettingsLabel.topAnchor.constraint(equalTo: basicSettingsView.topAnchor, constant: 16),
            basicSettingsLabel.leadingAnchor.constraint(equalTo: basicSettingsView.leadingAnchor, constant: 16),
            
            basicSettingsStackView.topAnchor.constraint(equalTo: basicSettingsLabel.bottomAnchor, constant: 16),
            basicSettingsStackView.leadingAnchor.constraint(equalTo: basicSettingsView.leadingAnchor),
            basicSettingsStackView.trailingAnchor.constraint(equalTo: basicSettingsView.trailingAnchor),
            basicSettingsStackView.bottomAnchor.constraint(equalTo: basicSettingsView.bottomAnchor, constant: -16),
            
            // About
            aboutView.topAnchor.constraint(equalTo: basicSettingsView.bottomAnchor, constant: 16),
            aboutView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            aboutView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            aboutView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16),
            
            aboutLabel.topAnchor.constraint(equalTo: aboutView.topAnchor, constant: 16),
            aboutLabel.leadingAnchor.constraint(equalTo: aboutView.leadingAnchor, constant: 16),
            
            aboutStackView.topAnchor.constraint(equalTo: aboutLabel.bottomAnchor, constant: 16),
            aboutStackView.leadingAnchor.constraint(equalTo: aboutView.leadingAnchor),
            aboutStackView.trailingAnchor.constraint(equalTo: aboutView.trailingAnchor),
            aboutStackView.bottomAnchor.constraint(equalTo: aboutView.bottomAnchor, constant: -16)
        ])
    }
    
    // MARK: - Actions
    @objc private func learnMoreTapped() {
        // 显示使用指南
        let alert = UIAlertController(title: "使用指南", message: """
        智能扫描仪使用指南：
        
        📱 OCR识别：拍照或选择图片，快速识别文字
        📄 文档扫描：自动优化文档图片质量
        🤖 AI翻译：智能翻译识别出的文字
        📏 手机测距：使用AR技术测量物体距离
        🖼️ 老照片：修复和优化老照片
        
        更多功能等你来发现！
        """, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "知道了", style: .default))
        present(alert, animated: true)
    }
    
    @objc private func toggleChanged(_ sender: UISwitch) {
        // 处理暗黑模式切换
        print("Toggle changed! isOn: \(sender.isOn)")
        ThemeManager.shared.isDarkMode = sender.isOn
        print("Dark mode changed to: \(sender.isOn)")
    }
    
    @objc private func toggleTouchDown(_ sender: UISwitch) {
        // 测试 toggle 是否能响应触摸事件
        print("Toggle touch down detected!")
    }
    
    @objc private func infoButtonTapped() {
        // Handle info button tap
        print("Info button tapped")
    }
    
    @objc private func buttonTapped(_ sender: UIButton) {
        // Handle button tap
        print("Button tapped: \(sender.title(for: .normal) ?? "")")
    }
    
    @objc private func settingItemTapped(_ gesture: UITapGestureRecognizer) {
        guard let containerView = gesture.view else { return }
        let titleHash = containerView.tag
        
        // 根据标题哈希值识别点击的项目
        if titleHash == "分享给朋友".hashValue {
            shareApp()
        } else if titleHash == "关于我们".hashValue {
            showAboutUs()
        } else if titleHash == "用户协议".hashValue {
            let webView = SKWebViewController()
            webView.webUrl = kSK_agreement_url
            navigationController?.pushViewController(webView, animated: true)
        } else if titleHash == "隐私协议".hashValue {
            let webView = SKWebViewController()
            webView.webUrl = kSK_privacy_url
            navigationController?.pushViewController(webView, animated: true)
        } else if titleHash == "技术支持".hashValue {
            let webView = SKWebViewController()
            webView.webUrl = kSK_connection_url
            navigationController?.pushViewController(webView, animated: true)
        } else if titleHash == "历史记录".hashValue {
            showHistory()
        }
    }
    
    private func shareApp() {
        let appName = "智能扫描仪"
        let appDescription = "一款功能强大的智能扫描应用，支持OCR识别、文档扫描、AI翻译、手机测距等功能。"
        let appStoreURL = "https://apps.apple.com/app/your-app-id" // 替换为实际的App Store链接
        
        let shareText = """
        \(appName)
        
        \(appDescription)
        
        下载链接：\(appStoreURL)
        """
        
        let activityViewController = UIActivityViewController(activityItems: [shareText], applicationActivities: nil)
        
        // 在iPad上需要设置popoverPresentationController
        if let popover = activityViewController.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityViewController, animated: true)
    }
    
    private func showAboutUs() {
        let aboutVC = AboutUsViewController()
        navigationController?.pushViewController(aboutVC, animated: true)
    }
    

    
    private func showHistory() {
        let historyVC = HistoryViewController()
        navigationController?.pushViewController(historyVC, animated: true)
    }
    
    @objc private func themeDidChange() {
        // 更新页面背景色
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : kAppColor
        
        // 更新scrollView背景色
        scrollView.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : kAppColor
        
        // 确保contentView背景色为透明
        contentView.backgroundColor = .clear
        
        // 重新设置UI以适配新主题
        setupProBanner()
        setupBasicSettings()
        setupAboutSection()
        
        // 重新创建设置项视图
        basicSettingsStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        aboutStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        
        for item in getBasicSettings() {
            let itemView = createSettingItemView(item: item)
            basicSettingsStackView.addArrangedSubview(itemView)
        }
        
        for item in aboutSettings {
            let itemView = createSettingItemView(item: item)
            aboutStackView.addArrangedSubview(itemView)
        }
    }
} 
